<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        body {
            width: 100%;
            height: 100%;
        }

        #box {
            width: 800px;
            height: 20px;
            /* margin: auto; */
            margin-left: -400px;
            position: absolute;
            left: 50%;
            top: 50%;
            border: 1px solid gray;
            box-sizing: border-box;
        }

        #box1 {
            height: 20px;
        }

        button {
            width: 50px;
            height: 30px;
            display: block;
            border: none;
            outline: none;
            background-color: gray;
            cursor: pointer;
            position: absolute;
            left: 50%;
            top: 60%;
            margin: -25px;
        }
    </style>
</head>

<body>
    <div id="box">
        <main id="box1"></main>
        <span id="sp"></span>
    </div>
    <button id="btn">下载</button>
    <script>
        var btn1 = document.getElementById('btn1')
        var sp = document.getElementById('sp')
        var box1 = document.getElementById('box1')
        btn.onclick = function () {
            // 定义一个进度，用来写入div的宽度
            var ti = 0.1
            var times = setInterval(function () {
                // 保留ti的两位小数点
                var to = ti.toFixed(2)
                // 设置width的宽度位to
                box1.style.width = to + "%"
                // span标签加入下载进度,让用户看得到百分之几
                sp.innerHTML = to + "%"
                box1.style.background = "red"
                // 每次定时器启动,都会进行ti+0.1
                ti = ti + 0.1
                /* 如果to大于100,那么说明下载完了,
                我们需要把进度条定在100 % 的状态, 然后清除定时器*/
                if (to > 100) {
                    box1.style.width = 100 + "%"
                    sp.innerHTML = 100 + "%"
                    clearInterval(times)
                    alert("下载完成")
                }
            }, 10)
        }
    </script>
</body>

</html>